package com.rabbit.validate.xss;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * xss校验(也可以通过对评论类提交的字符串encode来解决)
 *
 * @author zjw
 * @date 2022/02/17 22:05
 */
public class XssValidator implements ConstraintValidator<Xss, String> {

    private static final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />";

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.hasLength(value)) {
            Pattern pattern = Pattern.compile(HTML_PATTERN);
            Matcher matcher = pattern.matcher(value);
            return !matcher.matches();
        } else {
            return true;
        }
    }
}